package com.zhangxiaofanfan.hotcode.first;

/**
 * TODO
 *
 * @author zhangxiaofanfan
 * @date 2024-06-18 22:48:00
 */
public class HotCode047 {
    public static void main(String[] args) {

    }

    public TreeNode buildTree(int[] preorder, int[] inorder) {
        return generateSubTree(preorder, 0, preorder.length - 1, inorder, 0, inorder.length - 1);
    }

    public TreeNode generateSubTree(int[] preorder, int preLeft, int preRight, int[] inorder, int inLeft, int inRight) {
        if (preLeft > preRight) {
            return null;
        }
        if (preLeft == preRight) {
            return new TreeNode(preorder[preLeft]);
        }
        int index;
        for (index = inLeft; index <= inRight; index++) {
            if (inorder[index] == preorder[preLeft]) {
                break;
            }
        }
        TreeNode node = new TreeNode(preorder[preLeft]);
        node.left = generateSubTree(preorder, preLeft + 1, preLeft + index - inLeft, inorder, inLeft, index - 1);
        node.right = generateSubTree(preorder, preLeft + index - inLeft + 1, preRight, inorder, index + 1, inRight);
        return node;
    }

    public class TreeNode {
        int val;
        TreeNode left;
        TreeNode right;

        TreeNode() {
        }

        TreeNode(int val) {
            this.val = val;
        }

        TreeNode(int val, TreeNode left, TreeNode right) {
            this.val = val;
            this.left = left;
            this.right = right;
        }
    }
}
